package com.yx.cloud.utils;

import android.content.Context;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.NetworkInfo.DetailedState;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.AuthAlgorithm;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager.WifiLock;
import android.os.Build;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.util.Log;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class WifiManager {
    private static final String TAG = "WifiManager";
    private static final int TYPE_NO_PASSWD = 0x11;
    private static final int TYPE_WEP = 0x12;
    private static final int TYPE_WPA = 0x13;
    public static final int WIFI_CONNECTED = 0x01;
    public static final int WIFI_CONNECT_FAILED = 0x02;
    public static final int WIFI_CONNECTING = 0x03;
    public static final String APPLIANCE_WIFI_FIRST_MARK = "TE-M001-"; // SMAP
    public static final String APPLIANCE_WIFI_HTTP_FIRST_MARK = "te-id=";
    public static final String APPLIANCE_WIFI_FIRST_MARK_HISENSE = "AIH-W401-";//海信科龙单体大模块
    public static final String APPLIANCE_WIFI_FIRST_MARK_HISENSE_KELON = "AIH-W411-";//海信科龙单体小模块
    public static final String APPLIANCE_WIFI_FIRST_MARK_HISENSE_JD = "AIH-W413-";//海信京东
    public static final String APPLIANCE_WIFI_FIRST_MARK_HISENSE_GUODIAN = "AIH-W417-";//海信国电
    public static final String APPLIANCE_WIFI_FIRST_MARK_HISENSE_OEM = "AEH-W4A1-";//外销机
    public static final String APPLIANCE_WIFI_FIRST_MARK_KELON = "AIK-W411-";//科龙单体小模块
    public static final String APPLIANCE_WIFI_FIRST_MARK_KELON_JD = "AIK-W413-";//科龙，对应海信京东
    public static final String APPLIANCE_WIFI_FIRST_MARK_SMARTBOX = "CMD-W01-";//第一代smartbox
    public static final String APPLIANCE_WIFI_FIRST_MARK_FT = "FT-JACGD-";//方太灶具
    public static final String APPLIANCE_WIFI_FIRST_MARK_FT_WATERHEATER = "FTT-R010-";//方太热水器
    public static final String APPLIANCE_WIFI_FIRST_MARK_XLF = "XLF-D401-";
    public static final String APPLIANCE_WIFI_FIRST_MARK_OVEN = "CST-";//烤箱
    public static final String APPLIANCE_WIFI_FIRST_MARK_OVEN_YIBAKER = "Yibaker_";//一焙烤箱
    public static final String APPLIANCE_WIFI_FIRST_MARK_PLANT_TE = "ZCT-";//种菜机
    public static final String APPLIANCE_WIFI_FIRST_MARK_PLANT_JF = "ZZT-";//种菜机
    public static final String APPLIANCE_WIFI_FIRST_MARK_DINCHEN = "DCT-";//鼎辰即热水
    public static final int APPLIANCE_WIFI_SSID_SIZE = 20;
    public static final int APPLIANCE_WIFI_HISENS_SSID_SIZE = 21;
    public static final String APPLIANCE_WIFI_DILIVER_CHAR = "_";

    // 定义WifiManager对象
    private android.net.wifi.WifiManager mWifiManager = null;
    private ConnectivityManager connectivityManager = null;
    private Context mContext = null;
    private List<ScanResult> mWifiDevicesList;
    private List<WifiConfiguration> mWifiConfiguration;
    private HashMap<String, List<ScanResult>> mApplianceScanResult = null;
    private WifiInfo mWifiInfo = null;
    private static WifiConfiguration routeInfo = null;
    // 网络连接列表
    private List<WifiConfiguration> mWifiConfigurationList;
    // 定义一个WifiLock
    private WifiLock mWifiLock = null;

    private static final int SECURITY_NONE = 0;
    private static final int SECURITY_WEP = 1;
    private static final int SECURITY_PSK = 2;
    private static final int SECURITY_EAP = 3;
    private static final int SECURITY_WPA = 4;
    private int connectType = -1;
    private static WifiManager Appliancewifimanager = null;

    public WifiManager(Context mContext) {
        this.mContext = mContext;
        mWifiManager = (android.net.wifi.WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
        connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        mApplianceScanResult = new HashMap<String, List<ScanResult>>();
    }

    public static WifiManager instance(Context mContext) {
        if (Appliancewifimanager == null) {
            Appliancewifimanager = new WifiManager(mContext);
        }
        return Appliancewifimanager;
    }

    // 打开WIFI
    public void openWifi() {
        if (null != mWifiManager) {
            if (!mWifiManager.isWifiEnabled()) {
                mWifiManager.setWifiEnabled(true);
            }
        }
    }

    public boolean isWifiEnable() {
        if (null != mWifiManager) {
            return mWifiManager.isWifiEnabled();
        }
        return false;
    }

    // 关闭WIFI
    public void closeWifi() {
        if (null != mWifiManager) {
            if (mWifiManager.isWifiEnabled()) {
                mWifiManager.setWifiEnabled(false);
            }
        }
    }

    /**
     * 指定SSID是否在当前wifi列表里，会有扫描延时2s
     *
     * @param ssid
     * @return 指定SSID在当前wifi列表里返回该SSID的ScanResult，否则返回null
     */
    public ScanResult isApplianceWifiOpened(String ssid) {
        if (null != mWifiManager) {
            if (isWifiEnable()) {
                startScan();
                for (ScanResult currentResult : mWifiDevicesList) {
                    if (currentResult.SSID.contains(convertSSIDToLowerCase(ssid))) {
                        return currentResult;
                    }
                }
            } else {
                Log.e(TAG, "wifi disabled");
            }
        }
        return null;
    }

    private WifiConfiguration isWifiConfigExsits(String SSID) {
        if (null != mWifiManager) {
            List<WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();
            if (null == existingConfigs) {
                return null;
            }
            for (WifiConfiguration existingConfig : existingConfigs) {
                if (existingConfig.SSID.equals("\"" + convertSSIDToLowerCase(SSID) + "\"")) {
                    return existingConfig;
                }
            }
        }
        return null;
    }

    /**
     * 获取wifi连接状态，判断是否连接成功,不是network
     *
     * @param
     * @return
     */
    public int isWifiConnected() {
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        Log.v(TAG, "isConnectedOrConnecting = " + wifiNetworkInfo.isConnectedOrConnecting());
//		LogUtils.v(TAG, "wifiNetworkInfo.getDetailedState() = " + wifiNetworkInfo.getDetailedState());
        if (wifiNetworkInfo.getDetailedState() == DetailedState.OBTAINING_IPADDR
                || wifiNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
            return WIFI_CONNECTING;
        } else if (wifiNetworkInfo.getDetailedState() == DetailedState.CONNECTED) {
            return WIFI_CONNECTED;
        } else {
            return WIFI_CONNECT_FAILED;
        }
    }

    /**
     * // 断开指定ID的网络
     *
     * @param netId
     */
    public void disconnectWifi(int netId) {
        if (null != mWifiManager) {
            mWifiManager.disableNetwork(netId);
            mWifiManager.disconnect();
        }
    }

    /**
     * 断开当前连接的网络
     */
    public void disconnectWifi() {
        WifiInfo mWifiInfo = getConnectedWifiInfo();
        if (mWifiInfo != null) {
            mWifiManager.disableNetwork(mWifiInfo.getNetworkId());
            mWifiManager.disconnect();
        }
    }

    public static boolean isApplianceWifi(String ssid) {

        if (null == ssid) {
            return false;
        }

        if (ssid.contains(WifiManager.APPLIANCE_WIFI_FIRST_MARK)
                || ssid.contains(WifiManager.APPLIANCE_WIFI_FIRST_MARK_HISENSE)
                || ssid.contains(WifiManager.APPLIANCE_WIFI_FIRST_MARK_HISENSE_KELON)
                || ssid.contains(WifiManager.APPLIANCE_WIFI_FIRST_MARK_HISENSE_JD)
                || ssid.contains(WifiManager.APPLIANCE_WIFI_FIRST_MARK_HISENSE_GUODIAN)
                || ssid.contains(WifiManager.APPLIANCE_WIFI_FIRST_MARK_HISENSE_OEM)
                || ssid.contains(WifiManager.APPLIANCE_WIFI_FIRST_MARK_KELON)
                || ssid.contains(WifiManager.APPLIANCE_WIFI_FIRST_MARK_KELON_JD)
                || ssid.contains(WifiManager.APPLIANCE_WIFI_HTTP_FIRST_MARK)
                || ssid.contains(WifiManager.APPLIANCE_WIFI_FIRST_MARK_SMARTBOX)
                || ssid.contains(WifiManager.APPLIANCE_WIFI_FIRST_MARK_FT)
                || ssid.contains(WifiManager.APPLIANCE_WIFI_FIRST_MARK_FT_WATERHEATER)
                || ssid.contains(WifiManager.APPLIANCE_WIFI_FIRST_MARK_XLF)
                || ssid.contains(WifiManager.APPLIANCE_WIFI_FIRST_MARK_OVEN)
                || ssid.contains(WifiManager.APPLIANCE_WIFI_FIRST_MARK_OVEN_YIBAKER)
                || ssid.contains(WifiManager.APPLIANCE_WIFI_FIRST_MARK_PLANT_TE)
                || ssid.contains(WifiManager.APPLIANCE_WIFI_FIRST_MARK_PLANT_JF)
                || ssid.contains(WifiManager.APPLIANCE_WIFI_FIRST_MARK_DINCHEN)) {
            return true;
        } else {
            return false;
        }
    }

    /*断开家电连接*/
    public void disconnectCurrentApplianceWifi() {
        WifiInfo mWifiInfo = getConnectedWifiInfo();
        String ssid = mWifiInfo.getSSID();
        boolean isApplianceWifi = isApplianceWifi(ssid);
        if (isApplianceWifi) {
            disconnectWifi(mWifiInfo.getNetworkId());
        }
    }

    // 检查当前WIFI状态
    public int checkState() {
        if (null != mWifiManager) {
            return mWifiManager.getWifiState();
        }
        return 0x4;
    }

    // 锁定WifiLock
    public void acquireWifiLock() {
        mWifiLock.acquire();
    }

    // 解锁WifiLock
    public void releaseWifiLock() {
        // 判断时候锁定
        if (mWifiLock.isHeld()) {
            mWifiLock.acquire();
        }
    }

    // 创建一个WifiLock
    public void creatWifiLock() {
        if (null != mWifiManager) {
            mWifiLock = mWifiManager.createWifiLock("LiveHome");
        }
    }

    // 得到配置好的网络
    public List<WifiConfiguration> getConfiguration() {
        if (null != mWifiManager) {
            mWifiConfigurationList = mWifiManager.getConfiguredNetworks();
        }
        return mWifiConfigurationList;
    }

    // 指定配置好的网络进行连接	--WifiConfiguration列表也是变动的
    public void connectConfiguration(int index) {
        // 索引大于配置好的网络索引返回
        if (index > mWifiConfigurationList.size()) {
            return;
        }
        // 连接配置好的指定ID的网络
        mWifiManager.enableNetwork(mWifiConfigurationList.get(index).networkId, true);
    }

    // 得到网络列表
    public HashMap<String, List<ScanResult>> getWifiList() {
        return mApplianceScanResult;
    }

    /**
     * 获取当前连接的wifiInfo
     *
     * @return
     */
    public WifiInfo getConnectedWifiInfo() {
        if (null != mWifiManager) {
            if (mWifiManager.isWifiEnabled()) {
                mWifiInfo = mWifiManager.getConnectionInfo();
                return mWifiInfo;
            }
        }
        return null;
    }

    public String getConnectedSSID() {
        if (null != mWifiManager) {
            if (mWifiManager.isWifiEnabled()) {
                String thirdSSid = getWifiSSID();
                String extraInfo = null;
                NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
                if (networkInfo != null) {
                    extraInfo = networkInfo.getExtraInfo();
                }
                com.iot.common.utils.LogUtils.i(extraInfo);
                com.iot.common.utils.LogUtils.i(thirdSSid);
                if (!isEmptySSID(thirdSSid)) {
                    return thirdSSid;
                }
                if (!isEmptySSID(extraInfo)) {
                    return extraInfo;
                }
            }
        }
        return "";
    }

    public String getWifiSSID() {
        mWifiInfo = mWifiManager.getConnectionInfo();
        String ssid = mWifiInfo.getSSID();
        com.iot.common.utils.LogUtils.i(ssid);
        if (!isEmptySSID(ssid)) {
            return ssid;
        }
        int networkId = mWifiInfo.getNetworkId();
        List<WifiConfiguration> configuredNetworks = mWifiManager.getConfiguredNetworks();
        for (WifiConfiguration wifiConfiguration : configuredNetworks) {
            if (wifiConfiguration.networkId == networkId) {
                ssid = wifiConfiguration.SSID;
                break;
            }
        }
        return ssid;
    }

    private boolean isEmptySSID(String ssid) {
        if (TextUtils.isEmpty(ssid) || "<unknown ssid>".equals(ssid)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 线程会sleep 2s，最好在子线程中scan
     */
    public void startScan() {
        if (null != mWifiManager) {
            Log.e(TAG, "mWifiManager a :");
            mWifiManager.startScan();
            // scan需要1.4s左右才能得到结果。最好在线程调用
            sleep(2000);
            // 得到扫描结果
            mWifiDevicesList = mWifiManager.getScanResults();
            Log.e(TAG, "mWifiDevicesList  :" + mWifiDevicesList.size());
            // 得到配置好的网络连接
            mWifiConfiguration = mWifiManager.getConfiguredNetworks();
        } else {
            Log.e(TAG, "mWifiManager  :" + mWifiManager);
        }
    }

    /**
     * 获取当前wifi列表，会有扫描延时2s
     *
     * @return
     */
    public List<ScanResult> getDeviceList() {
        // wifi列表时刻在改变，要想取得当前正确的列表必须先scan
        startScan();
        return mWifiDevicesList;
    }

    /**
     * 获取设备AP列表，会有扫描延时2s
     *
     * @return
     */
    public List<ScanResult> getApplianceApList() {
        startScan();
        if (mWifiDevicesList != null && mWifiDevicesList.size() > 0) {
            List<ScanResult> apList = new ArrayList<ScanResult>();
            for (ScanResult scanResult : mWifiDevicesList) {
                if (isApplianceWifi(scanResult.SSID)) {
                    apList.add(scanResult);
                }
            }
            return apList;
        }
        return null;
    }

    // 得到连接的ID
    public int getNetworkId() {
        mWifiInfo = getConnectedWifiInfo();
        return (mWifiInfo == null) ? -1 : mWifiInfo.getNetworkId();
    }

    /**
     * 根据SSID返回WifiConfiguration的networkId
     *
     * @param SSID
     * @return
     */
    public int getNetworkId(String SSID) {
        if (!TextUtils.isEmpty(SSID)) {
            WifiConfiguration wifiConfiguration = getWifiConfig(SSID);
            if (wifiConfiguration != null) {
                return wifiConfiguration.networkId;
            }
        }
        return -1;
    }

    // 查看扫描结果
    public StringBuilder lookUpScan() {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < mWifiDevicesList.size(); i++) {
            stringBuilder.append("Index_" + new Integer(i + 1).toString() + ":");
            // 将ScanResult信息转换成一个字符串包
            // 其中把包括：BSSID、SSID、capabilities、frequency、level
            stringBuilder.append((mWifiDevicesList.get(i)).toString());
            stringBuilder.append("/n");
        }
        return stringBuilder;
    }

    /**
     * 根据指定ssid获取WiFiConfiguration配置
     *
     * @param ssid
     * @return
     */
    public WifiConfiguration getWifiConfig(String ssid) {
        if (null != mWifiManager) {
            List<WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();
            if (null != existingConfigs && existingConfigs.size() > 0) {
                for (WifiConfiguration existingConfig : existingConfigs) {
                    if (existingConfig.SSID.equals("\"" + convertSSIDToLowerCase(ssid) + "\"")) {
                        return existingConfig;
                    }
                }
            }
        }
        return null;
    }

    // 得到WifiInfo的所有信息包
    public String getWifiInfo() {
        mWifiInfo = getConnectedWifiInfo();
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.toString();
    }

    /**
     * 判断是否移动连接  GPRS,3G是否可用
     *
     * @return
     */
    public boolean isMobileNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        if (networkInfo != null && networkInfo.isConnected()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断WIFI是否连接上
     *
     * @return
     */
    public boolean isNetworkWifiConnected() {
        if (null != mWifiManager) {
            boolean isWifiEnable = mWifiManager.isWifiEnabled();
            if (isWifiEnable) {
                if (isWifiConnected() != WIFI_CONNECTED) {
                    return false;
                }
                return true;
            }
        }
        return false;
    }

    /**
     * 判断家电是否连接
     *
     * @return
     */
    public boolean isApplianceWifiConnected() {
        if (null != mWifiManager) {
            if (isNetworkWifiConnected()) {
                Log.d(TAG, "isNetworkWifiConnected = true");
                mWifiInfo = getConnectedWifiInfo();
                if (null == mWifiInfo) {
                    Log.d(TAG, "mWifiInfo = null");
                    return false;
                }
                Log.d(TAG, "getSSID = " + mWifiInfo.getSSID());
                if (isApplianceWifi(mWifiInfo.getSSID())) {
                    Log.d(TAG, "isApplianceWifi = true");
                    return true;
                } else {
                    Log.d(TAG, "isApplianceWifi = false");
                }
            }
        }
        return false;
    }

    /**
     * 网络是否可用，家电AP除外
     *
     * @param mContext
     * @return
     */
    public boolean isNetworkAvailable(Context mContext) {

        if (null != mWifiManager) {
            if (isMobileNetworkAvailable()) {
                return true;
            }

            if (!isNetworkWifiConnected()) {
                return false;
            }

            if (isApplianceWifiConnected()) {
                return false;
            }
            return true;
        }
        return false;
    }

    /**
     * 家电是否在网络配置中，已连接不作在网络，会有扫描延时2s ?
     *
     * @param ssid
     * @return
     */
    public ScanResult isApplianceWifiAvailable(String ssid) {
//		if (null == ssid) {
//			return null;
//		}
//		if (!isNetworkWifiConnected()) {
//			return null;
//		}
//		if (isApplianceWifiConnected()) {
//			return null;
//		}
//		if (null != mWifiManager) {
//			if (ssid.contains(WifiManager.APPLIANCE_WIFI_HTTP_FIRST_MARK)) {
//				int index = ssid.indexOf(Constants.CMD_AT_EQUALS_SINGNAL);
//				ssid = ssid.substring(index + 1);
//			}
//			/* 在扫描结果中匹配 */
//			startScan();
//			for (ScanResult current : mWifiDevicesList) {
//				if (ssid.equalsIgnoreCase(current.SSID)) {
//					return current;
//				}
//			}
//		}
        return null;
    }

    /**
     * 获取指定ssid的ScanResult，会有扫描延时2s
     *
     * @param ssid
     * @return
     */
    public ScanResult getScanResult(String ssid) {
        if (null == ssid) {
            return null;
        }

//		if (!isNetworkWifiConnected()) {
//			return null;
//		}

        if (null != mWifiManager) {
            Log.i(TAG, "===================== = " + ssid);

            /* 在扫描结果中匹配 */
            startScan();
            Log.i(TAG, "mWifiDevicesList.size() =  " + mWifiDevicesList.size());
            for (ScanResult current : mWifiDevicesList) {
                Log.i(TAG, "ssid = " + current.SSID);
                if (ssid.equalsIgnoreCase(current.SSID)) {
                    return current;
                }
            }
        }

        return null;
    }

    /**
     * 是否为有效的wifi网络
     *
     * @return
     */
    public boolean isWifiNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        if (networkInfo != null && networkInfo.isConnected()) {
            return true;
        } else {
            return false;
        }
    }

    /* 新方法只适用于4.0以后 */
    /* 获取当前IP */
    public int getConnectedWifiIp() {
        mWifiInfo = getConnectedWifiInfo();
        return mWifiInfo == null ? 0 : mWifiInfo.getIpAddress();
    }

    public String filterConnectedWifiSSID(String sourceSSID) {

        if (TextUtils.isEmpty(sourceSSID)) {
            return null;
        }
        int ssidLength = sourceSSID.length();

        if (String.valueOf(sourceSSID.charAt(0)).equals("\"")
                && String.valueOf(sourceSSID.charAt(ssidLength - 1)).equals("\"")) {
            return sourceSSID.substring(1, ssidLength - 1);
        }
        return sourceSSID;
    }

//	public String getCurrentWifiAddress() {
//		return Util.intToIp(getConnectedWifiIp());
//	}

    /**
     * 获得当前连接的wifi的ssid
     *
     * @return
     */
    public String getCurrentWifiSSID() {
        if (null != mWifiManager) {
            if (mWifiManager.isWifiEnabled()) {
                mWifiInfo = getConnectedWifiInfo();
                if (null == mWifiInfo) {
                    return null;
                }

                return convertSSIDToUpperCase(filterConnectedWifiSSID(mWifiInfo.getSSID()));
            }
        }
        return null;
    }

    public WifiInfo getCurrentWifiInfo() {
        if (null != mWifiManager) {
            if (mWifiManager.isWifiEnabled()) {
                WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
                if (null == wifiInfo) {
                    return null;
                }

                return wifiInfo;
            }
        }
        return null;
    }

    // 得到MAC地址
    public String getMacAddress() {
        mWifiInfo = getConnectedWifiInfo();
        return (mWifiInfo == null) ? null : mWifiInfo.getMacAddress();
    }

    // 得到接入点的BSSID
    public String getBSSID() {
        mWifiInfo = getConnectedWifiInfo();
        return (mWifiInfo == null) ? null : mWifiInfo.getBSSID();
    }

    public String getSSID() {
        return getCurrentWifiSSID();
    }
//	// 得到IP地址
//	public String getIPAddress() {
//		return getCurrentWifiAddress();
//	}

    // 得到网关地址
    public String getGatewayAddress() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {

        } else {
            if (null != mWifiManager) {
                String Ip = Formatter.formatIpAddress(mWifiManager.getDhcpInfo().gateway);
                Log.d(TAG, "Get gateway Ip : " + Ip);
                return Ip;
            }
        }
        return null;
    }

    /* 获得广播地址 */
    public String getBroadcastAddress() {
        if (null != mWifiManager) {
            DhcpInfo myDhcpInfo = mWifiManager.getDhcpInfo();
            if (myDhcpInfo == null) {
                Log.e(TAG, "Could not get broadcast address");
                return null;
            }
            int broadcast = (myDhcpInfo.ipAddress & myDhcpInfo.netmask) | ~myDhcpInfo.netmask;
            byte[] quads = new byte[4];
            for (int k = 0; k < 4; k++)
                quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
            try {
                return InetAddress.getByAddress(quads).toString();
            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }

    private int getSecurity(ScanResult result) {
        if (result.capabilities.contains("WEP")) {
            return SECURITY_WEP;
        } else if (result.capabilities.contains("PSK")) {
            return SECURITY_PSK;
        } else if (result.capabilities.contains("EAP")) {
            return SECURITY_EAP;
        }
        return SECURITY_NONE;
    }

    private String convertSSIDToLowerCase(String SSID) {
        if (TextUtils.isEmpty(SSID)) {
            return null;
        }

        if (!SSID.toUpperCase().startsWith(APPLIANCE_WIFI_FIRST_MARK_SMARTBOX)
                && !SSID.startsWith(APPLIANCE_WIFI_FIRST_MARK_OVEN)
                && !SSID.startsWith(APPLIANCE_WIFI_FIRST_MARK_OVEN_YIBAKER)) {
            if (isApplianceWifi(SSID)) {
                return toLowerCase(SSID, SSID.substring(SSID.length() - 12));
            } else {
                return SSID;
            }
        } else {
            return SSID;
        }
    }

    private String convertSSIDToUpperCase(String SSID) {
        if (TextUtils.isEmpty(SSID)) {
            return null;
        }

        if (!SSID.toUpperCase().startsWith(APPLIANCE_WIFI_FIRST_MARK_SMARTBOX)
                && !SSID.startsWith(APPLIANCE_WIFI_FIRST_MARK_OVEN)
                && !SSID.startsWith(APPLIANCE_WIFI_FIRST_MARK_OVEN_YIBAKER)) {
            if (isApplianceWifi(SSID)) {
                return toUpperCase(SSID, SSID.substring(SSID.length() - 12));
            } else {
                return SSID;
            }
        } else {
            return SSID;
        }
    }

    private String toLowerCase(String str, String sub) {
        return str.replaceAll(sub, sub.toLowerCase());
    }

    private String toUpperCase(String str, String sub) {
        return str.replaceAll(sub, sub.toUpperCase());
    }

    private String convertToQuotedString(String string) {
        return "\"" + string + "\"";
    }

    /* 按配置和ssid进行连接 */
    private void connect(WifiConfiguration config, String SSID, int security, String password) {

        Log.e(TAG, "connect    !");

        config.SSID = convertToQuotedString(convertSSIDToLowerCase(SSID));
        config.hiddenSSID = true;
        Log.e(TAG, "SSID    :" + config.SSID);
        switch (security) {
            case SECURITY_NONE:
                Log.e(TAG, "SECURITY_NONE    !");

                config.allowedKeyManagement.set(KeyMgmt.NONE);
                break;

            case SECURITY_WEP:
                Log.e(TAG, "SECURITY_WEP    !");
                config.allowedKeyManagement.set(KeyMgmt.NONE);
                config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
                config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED);
                if (password.length() != 0) {
                    int length = password.length();
                    // WEP-40, WEP-104, and 256-bit WEP (WEP-232?)
                    if ((length == 10 || length == 26 || length == 58) && password.matches("[0-9A-Fa-f]*")) {
                        config.wepKeys[0] = password;
                    } else {
                        config.wepKeys[0] = '"' + password + '"';
                    }
                }
                break;

            case SECURITY_PSK:
                Log.e(TAG, "SECURITY_PSK    !");
                config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
                if (password.length() != 0) {
                    if (password.matches("[0-9A-Fa-f]{64}")) {
                        config.preSharedKey = password;
                    } else {
                        config.preSharedKey = '"' + password + '"';
                    }
                }
                break;

            default:
                break;
        }

        connectWcg((config));
    }

    private WifiConfiguration createWifiInfo() {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        return config;
    }

    // 查看以前是否也配置过这个网络
    private WifiConfiguration isExsits(String SSID) {
        List<WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();
        if (existingConfigs == null) {
            return null;
        }
        for (WifiConfiguration existingConfig : existingConfigs) {
            if (existingConfig.SSID.equals(SSID)) {
                return existingConfig;
            }
        }
        return null;
    }

    private void connectWcg(WifiConfiguration wcg) {

        Log.e(TAG, "connectWcg   !");

        if (null != mWifiManager) {
            Log.e(TAG, "begin to add network");
            int wcgID = -1;
            if (Build.VERSION.SDK_INT > 22) {
                WifiConfiguration isexit = isExsits(wcg.SSID);
                if (isexit != null) {
                    wcgID = isexit.networkId;
                    Log.e(TAG, "wcgID  :" + wcgID);
                }
                if (wcgID == -1) { // 此处新增
                    wcgID = this.mWifiManager.addNetwork(wcg);
                    Log.e(TAG, "end to add network 1111 wcg :" + wcgID);
                }
            } else {
                Log.e(TAG, "else   :" + wcg.SSID);
                removeNetworkConfig(filterConnectedWifiSSID(wcg.SSID));
                wcgID = this.mWifiManager.addNetwork(wcg);
            }

            Log.e(TAG, "end to add network");
            if (wcgID != -1) {
                Log.e(TAG, "begin to enable network");
                if (!this.mWifiManager.enableNetwork(wcgID, true)) {
                    Log.e(TAG, "enable network failed");
                }

                Log.e(TAG, "end to enable network");
            } else {
                Log.e(TAG, "add network failed");
            }
        } else {
            Log.e(TAG, "mWifiManager null   !");
        }
    }

    /**
     * 根据指定的WifiConfiguration来连接wifi
     *
     * @param config
     */
    public void enableNetwork(WifiConfiguration config) {
        int networkId = getNetworkId(filterConnectedWifiSSID(config.SSID));
        if (networkId != -1 && getScanResult(filterConnectedWifiSSID(config.SSID)) != null) {
            mWifiManager.enableNetwork(networkId, true);
        } else {
            connectWcg(config);
        }
    }

    synchronized public void connectWifi(ScanResult mScanResult, String password) {
        if (null != mScanResult) {
            connect(createWifiInfo(), mScanResult.SSID, getSecurity(mScanResult), password);
        }
    }

    /**
     * 连接路由器
     *
     * @param
     * @param password
     */
    synchronized public void connectRouter(ScanResult mScanResult, String password) {
        if (null != mScanResult) {
            int networkId = getNetworkId(mScanResult.SSID);
            if (networkId != -1) {
                WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
                if (wifiInfo.getSSID().equals("\"" + mScanResult.SSID + "\"")) {
                    mWifiManager.disableNetwork(networkId);
                }
                mWifiManager.enableNetwork(networkId, true);
            } else {
                connect(createWifiInfo(), mScanResult.SSID, getSecurity(mScanResult), password);
            }
        }
    }

    /**
     * 连接设备AP，无需密码
     *
     * @param mScanResult
     */
    synchronized public void connectApplianceAP(ScanResult mScanResult) {
//		if (null != mScanResult) {
//			connect(createWifiInfo(), mScanResult.SSID, getSecurity(mScanResult), Util.getPassWord(mScanResult.SSID));
//		}
    }

    /**
     * 连接设备AP，需密码
     *
     * @param mScanResult
     * @param password
     */
    synchronized public void connectApplianceAP(ScanResult mScanResult, String password) {
        if (null != mScanResult) {
            if (null == password) {
                password = "";
            }
            connect(createWifiInfo(), mScanResult.SSID, getSecurity(mScanResult), password);
        }
    }

    /**
     * 连接设备AP，需要密码和加密类型
     *
     * @param ssid
     * @param password
     * @param wifiCipherType 加密类型：SECURITY_NONE：0，SECURITY_WEP = 1，SECURITY_PSK = 2，
     *                       SECURITY_EAP = 3，SECURITY_WPA = 4;
     */
    synchronized public boolean connectAPWithType(String ssid, String password, int wifiCipherType) {
        boolean status = false;
        if (ssid == null || password == null) {
            Log.e(TAG, "ssid or password is invalid!");
        }
        // 如果wifi关闭则打开wifi
        int retry = 5;
        while (!isWifiEnable() && --retry > 0) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            openWifi();
        }
        if (!isWifiEnable()) {
            Log.e(TAG, "open wifi failed");
            return false;
        }

        retry = 10;
        do {
            status = false;
            connect(createWifiInfo(), ssid, wifiCipherType, password);
            try {
                Thread.sleep(7000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            status = isNetworkWifiConnected();
            if (status) {
                String currssid = getCurrentWifiSSID();
                status = false;
                if (null != currssid) {
                    currssid = filterConnectedWifiSSID(currssid);
                    if (currssid.equalsIgnoreCase(ssid)) {
                        status = true;
                        break;
                    }
                }
                status = false;
            }
            Log.v(TAG, "wifi connect status = " + status);
        } while (--retry > 0);
        return status;
    }

    synchronized public boolean connectAPWithScanResult(String ssid, String password) {
        Log.e(TAG, "connectAPWithScanResult    !");
        boolean status = false;
        if (ssid == null || password == null) {
            Log.e(TAG, "connectAPWithScanResult ssid or password is invalid!");
        }
        // 如果wifi关闭则打开wifi
        int retry = 10;
        while (!isWifiEnable() && --retry > 0) {
            openWifi();
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
        if (!isWifiEnable()) {
            Log.e(TAG, "connectAPWithScanResult open wifi failed");
            return false;
        }
        ScanResult mScanResult = getScanResult(ssid);
        Log.e(TAG, "connectAPWithScanResult ssid  :" + ssid);
        if (null != mScanResult) {
            Log.e(TAG, "connectAPWithScanResult mScanResult    !");
            retry = 5;
            do {
                status = false;
                connect(createWifiInfo(), ssid, getSecurity(mScanResult), password);
                try {
                    Thread.sleep(7000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                status = isNetworkWifiConnected();

                if (status) {
                    String currssid = getCurrentWifiSSID();
                    status = false;
                    if (null != currssid) {
                        currssid = filterConnectedWifiSSID(currssid);
                        if (currssid.equalsIgnoreCase(ssid)) {
                            status = true;
                            break;
                        }
                    }
                    status = false;
                }
                Log.v(TAG, "connectAPWithScanResult wifi connect status = " + status);
            } while (--retry > 0);
        } else {
            Log.e(TAG, "connectAPWithScanResult mScanResult    null !");
            status = false;
        }
        return status;
    }

    /* 是否连到家电，并取家电的配置 */
    public ScanResult isWifiConfigOpened(String ssid) {
        if (!isWifiEnable()) {
            openWifi();
        }
        if (null != mWifiManager) {
//			deleteNetworkConfig(ssid);
//			mWifiManager.startScan();
//			List<ScanResult> mWifiDevicesList = mWifiManager.getScanResults();
            startScan();
            for (ScanResult currentResult : mWifiDevicesList) {
                if (currentResult.SSID.equals(convertSSIDToLowerCase(ssid)) && isNetworkWifiConnected()) {

                    return currentResult.SSID.equals(getCurrentWifiSSID()) ? currentResult : null;
                }
            }
        }
        Log.e(TAG, "connectAPWithScanResult No scan to this " + ssid + " config!");
        return null;
    }

    /* 切换到家电 */
    public boolean switchToConnectAppliance(String ssid, int maxtimes) {
        if (!isWifiEnable()) {
            Log.e(TAG, "switch_Route:wifi is close!!!");
            return false;
        }

        if (null != isWifiConfigOpened(ssid)) {
            Log.d(TAG, "switch_Route:wifi is Appliance!!!");
            return true;
        }

        if (isApplianceWifiConnected()) {
            Log.e(TAG, "switch_Route:wifi is other Appliance!!!");
            return false;
        }
        if (null != mWifiManager) {
            if (null == routeInfo) {
                routeInfo = getWifiConfig(getCurrentWifiSSID());
            }
            long time = System.currentTimeMillis();
            while (System.currentTimeMillis() - time < maxtimes) {
                ScanResult mScanResult = getScanResult(ssid);
                if (null != mScanResult) {
                    connectApplianceAP(mScanResult);
                }
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if (null != isWifiConfigOpened(ssid)) {
                    return true;
                }
            }
        }
        return false;

    }

    public boolean saveRouterInfo() {
        if (!isWifiEnable()) {
            Log.e(TAG, "switch_Route:wifi is close!!!");
            return false;
        }

        if (isApplianceWifiConnected()) {
            Log.e(TAG, "switch_Route:wifi is other Appliance!!!");
            return false;
        }
        if (null != mWifiManager) {
            routeInfo = getWifiConfig(getCurrentWifiSSID());
            return true;
        }
        return false;
    }

    synchronized public boolean switchToConnectRouter(int maxtimes) {

        if (!isWifiEnable()) {
            Log.e(TAG, "switch_Route:wifi is close!!!");
            return false;
        }

        if (null == routeInfo) {
            Log.e(TAG, "switch_Route:route not save!!!");
            return false;
        }
        if (null != mWifiManager) {
            long time = System.currentTimeMillis();
            while (System.currentTimeMillis() - time < maxtimes) {

                enableNetwork(routeInfo);

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if (null != isWifiConfigOpened(filterConnectedWifiSSID(routeInfo.SSID))) {
                    return true;
                }
            }
            Log.e(TAG, "switch_Route:connect timeout!!!");
        }
        return false;
    }

    public String getroutessid() {
        if (null != routeInfo) {
            return filterConnectedWifiSSID(routeInfo.SSID);
        }
        return null;
    }

    /**
     * 删除一个网络配置
     *
     * @param ssid
     */
    public void removeNetworkConfig(String ssid) {
        WifiInfo mWifiInfo = null;
        if (null != mWifiManager) {
            if (ssid.equals("")) {
                mWifiInfo = getConnectedWifiInfo();
            }
            Log.i(TAG, " :--配网--断开当前连接设备热点-222 --->" + mWifiInfo.getSSID());
            // 存在的话先删掉，不然config列表会一直增加
            WifiConfiguration tempConfig = isWifiConfigExsits(mWifiInfo.getSSID());
            if (tempConfig != null) {
                mWifiManager.removeNetwork(tempConfig.networkId);
            }
        }
    }

    private void sleep(long time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public ScanResult isAPWifiOpened(String ssid) {
        if (!isWifiEnable()) {
            openWifi();
        }

        mWifiManager.startScan();
        List<ScanResult> mWifiDevicesList = mWifiManager.getScanResults();
        for (ScanResult currentResult : mWifiDevicesList) {
            if (currentResult.SSID.equals(convertSSIDToLowerCase(ssid))) {
                return currentResult;
            }
        }

        Log.e(TAG, "No scan to this " + ssid + " ap or 4004!");
        return null;
    }

    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     *
     * @param context
     * @return true 表示开启
     */
    public static boolean isOPen(final Context context) {
        LocationManager locationManager
                = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }
        return false;
    }
}
